package com.aqie.easy.math;

import java.util.Arrays;

/**
 * 1137 泰波那契数
 */
public class Tribonacci {
    /**
     * 1. 记忆化搜索
     */
    private int[] memo;
    public int tribonacci(int n) {
        memo = new int[n + 1];
        Arrays.fill(memo, -1);
        return getTribonacci(n);
    }


    private int getTribonacci(int n) {
        if (n == 0) {
            return 0;
        }
        if (n == 1) {
            return 1;
        }
        if (n == 2) {
            return 1;
        }

        if (memo[n] == -1) {
            memo[n] = getTribonacci(n - 1) + getTribonacci(n - 2) + getTribonacci(n - 3);
        }

        return memo[n];
    }


    public int tribonacci2(int n) {
        int prev = 0;
        int curr = 1;
        int next = 1;
        while(n-- > 0){
            next = next + curr + prev;
            curr = next - curr - prev;
            prev = next -prev - curr;
        }
        return prev;
    }

    /**
     * 3. 动态规划
     * @param n
     * @return
     */
    public int tribonacci3(int n) {
        if (n == 0) {
            return 0;
        }
        if (n == 1) {
            return 1;
        }
        if (n == 2) {
            return 1;
        }

        int[] dp = new int[n + 1];

        dp[0] = 0;
        dp[1] = 1;
        dp[2] = 1;

        for (int i = 3; i <= n; i++) {
            dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3];
        }

        return dp[n];
    }


    public static void main(String[] args) {
        System.out.println(new Tribonacci().tribonacci(25));
    }
}
